package com.fs.jzzn.service;

import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Data;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.fs.jzzn.pojo.Expense;
import com.fs.jzzn.pojo.ExpenseItem;
import com.fs.jzzn.repository.ExpenseItemRepository;
import com.fs.jzzn.repository.ExpenseRepository;

@AllArgsConstructor
@Data
@Service("expenseService")
public class ExpenseService {
	private ExpenseRepository expenseRepository;
	private ExpenseItemRepository expenseItemRepository;
	
	@Transactional
	public String saveOrUpdata(Expense expense,List<ExpenseItem> childs){
		/*
		 * 删除关联子数据
		 */
		if(StringUtils.isNotBlank(expense.getExpenseNo())){
			expenseItemRepository.deleteByExpenseNo(expense.getExpenseNo());
		}
		/*
		 * 保存子
		 */
		if(!CollectionUtils.isEmpty(childs)){
			for(ExpenseItem item: childs){
				item.setCreaterId(expense.getCreaterId());
				item.setExpenseNo(expense.getExpenseNo());
			}
			expenseItemRepository.save(childs);
		}
		/*
		 * 保存父
		 */
		expense = expenseRepository.save(expense);
		
		return expense.getId();
	}
	
	/**
	 * 级联删除父子相关数据
	 * @param id
	 */
	@Transactional
	public void delete(String id){
		Expense expense = expenseRepository.findOne(id);
		String expenseNo = expense.getExpenseNo();
		expenseRepository.delete(id);
		expenseItemRepository.deleteByExpenseNo(expenseNo);
	}
}
